package com.hx.zhg.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @description: 远程客户端处理工具类
 */
public class RemoteClientUtil {
	
	/**
	 * @Description:得到客户端访问IP
	 * @data: 2014年7月6日 下午10:14:16
	 * @author：shikebing
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if(ip == null) {
			ip = "";
		}
		return ip;
	}

	/**
	 * 在linux环境下得到ip对应的host信息
	 * @param ip
	 * @return 返回信息如：251.65.249.66.in-addr.arpa domain name pointer crawl-66-249-65-251.googlebot.com.
	 * @throws IOException
	 */
	public static String getHostInfoByIpAddrInLinux(String ip) throws IOException {
		if (StringUtils.isEmpty(ip)) {
			return "";
		}
		Process process = null;
		BufferedReader reader = null;
		try {
			process = Runtime.getRuntime().exec("host " + ip);
			reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = "";
			StringBuilder hostInfo = new StringBuilder();
			while ((line = reader.readLine()) != null) {
				hostInfo.append(line);
			}
			return hostInfo.toString();
		}finally {
			if (reader != null) {
				reader.close();
			}
			process.destroy();
		}
	}
	
}
